package com.hao.tool.web.module.fileInfo.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ZipUtil;
import cn.hutool.extra.ftp.Ftp;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.hao.tool.common.constant.Commons;
import com.hao.tool.common.entity.LayResponse;
import com.hao.tool.web.component.properties.FTPProjectProperties;
import com.hao.tool.web.module.fileInfo.entity.TemplateInfo;
import com.hao.tool.web.module.fileInfo.service.TemplateService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * description
 *
 * @author RuiHaoZ on GZ.cmhk
 * @date 2019-11-22 23:37
 */
@RestController
@RequestMapping("/rest/template")
public class TemplateRestController {

    @Autowired
    private TemplateService templateService;
    @Autowired
    private FTPProjectProperties ftpProperties;


    @PostMapping("/add")
    public LayResponse upload(MultipartFile file, HttpServletRequest request) throws IOException {
        String dateStr = DateUtil.formatDate(new Date()).replace("-", "");
        String userName = (String) request.getAttribute(Commons.SUB_KEY);
        String repeatStatus = request.getParameter("repeatStatus");
        userName = StringUtils.isBlank(userName) ? "anonymous" : userName;
        Ftp ftp = new Ftp(ftpProperties.getFtpIp(), ftpProperties.getFtpPort(),
                ftpProperties.getFtpUsername(), ftpProperties.getFtpPassword());
        String savePath = ftpProperties.getBaseRootDir() + "templates/" + dateStr + "/";
        List<TemplateInfo> templateInfos = new ArrayList<>();
        String oriFileName = file.getOriginalFilename();
        boolean isExist = templateService.fileNameIsExist(oriFileName);
        if (isExist && StringUtils.isBlank(repeatStatus)) {
            return LayResponse.builder().code(201).msg("数据已经存在，可设置'repeatStatus'为1，强制上传")
                    .data(templateInfos).build();
        }

        boolean isUpload = ftp.upload(savePath, file.getOriginalFilename(), file.getInputStream());
        if (!isUpload) {
            return LayResponse.builder().code(201).msg("未上传成功").build();
        }
        String ftpBasePath = "/opt/hao_ftp/" + savePath + "/" + file.getOriginalFilename();

        File unZipFile = ZipUtil.unzip(ftpBasePath);
        if (!unZipFile.exists() || !unZipFile.isDirectory()) {
            return LayResponse.builder().code(202).msg("压缩包内无文件").build();
        }

        for (File listFile : unZipFile.listFiles()) {
            String fileType = ".html";
            if (listFile.getName().contains(fileType)) {

                TemplateInfo templateInfo = new TemplateInfo();
                templateInfo.setSourceName(oriFileName);
                templateInfo.setSourcePath(ftpBasePath);

                templateInfo.setId(IdWorker.getIdStr());
                templateInfo.setClickCount(0L);
                templateInfo.setCreateTime(LocalDateTime.now());
                templateInfo.setCreateUser(userName);
                templateInfo.setModType(fileType);
                templateInfo.setModPath(listFile.getAbsolutePath());

                String content = FileUtil.readUtf8String(listFile.getAbsolutePath());
                int be = content.indexOf("<title>");
                int end = content.lastIndexOf("</title>");
                if (be > 0 && end > 0) {
                    String modelName = content.substring(be + "<title>".length(), end);
                    templateInfo.setModName(modelName);
                }
                templateInfos.add(templateInfo);
            }
        }
        boolean isSave = templateService.saveBatch(templateInfos);
        return LayResponse.builder().code(200).msg(":" + (isSave)).data(templateInfos).build();

    }

}
